/*
 * Copyright (c) 2010 CCX(China) Co.,Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * CCX(China) Co.,Ltd. ("Confidential Information").
 * It may not be copied or reproduced in any manner without the express 
 * written permission of CCX(China) Co.,Ltd.
 *
 * Author: zhaosj
 * Date: 2010-10-13 上午09:55:51
 */
package com.webservice;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.activation.DataHandler;

/**
 * @author Administrator
 *
 */
public class FileService
{
   //  使用byte[]类型参数上传二进制文件
    public boolean uploadWithByte(byte[] file, String filename)
    {
         FileOutputStream fos = null;
         try
         {                          
             fos = new FileOutputStream(filename);    
             fos.write(file);
             fos.close();
         }
         catch (Exception e)
         {
             return false;
         }
         finally
         {
             if (fos != null)
             {
                 try
                 {
                     fos.close();
                 }
                 catch (Exception e)
                 {
                 }
             }
         }
         return true;
    }
    private void writeInputStreamToFile(InputStream is, OutputStream os) throws Exception
    {
         int n = 0;
         byte[] buffer = new byte[8192];
         while((n = is.read(buffer)) > 0)
         {
             os.write(buffer, 0, n);
         }
    }
    //  使用DataHandler类型参数上传文件
    public boolean uploadWithDataHandler(DataHandler file, String filename)
    {
        
         FileOutputStream fos = null;
         try
         {            
             fos = new FileOutputStream(filename);   
             //  可通过DataHandler类的getInputStream方法读取上传数据
             writeInputStreamToFile(file.getInputStream(), fos);
             fos.close();
         }
         catch (Exception e)
         {
             return false;
         }
         finally
         {
             if (fos != null)
             {
                 try
                 {
                     fos.close();
                 }
                 catch (Exception e)
                 {
                 }
             }
         }
         return true;
    }
}
